//
//  CXLPicturePickerViewController.swift
//  照片选择
//
//  Created by 曹晓龙 on 15/10/26.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

/// cell重用标示
private let CXLPicturePickerViewCellID = "CXLPicturePickerViewCellID"

/// 最大选中张数
private let maxPictureCount = 4

class CXLPicturePickerViewController: UICollectionViewController {

    /// 存放图片数组
    lazy var pictrues = [UIImage]()
    
    /// 选中的cell索引
    lazy var index = 0
    
    //MARK: - 构造方法
    init(){
        
        super.init(collectionViewLayout: CXLPicturePickerFlowLayout())
        
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 注册重用Cell
        self.collectionView!.registerClass(CXLPicturePickerCell.self, forCellWithReuseIdentifier: CXLPicturePickerViewCellID)

    }
    
    //MARK: - 自定义layout
    class CXLPicturePickerFlowLayout: UICollectionViewFlowLayout {
        
        override func prepareLayout() {
            
            super.prepareLayout()
            
            let cellCount:CGFloat = 4
            
            let margin = UIScreen.mainScreen().scale * 4
            
            let width = (collectionView!.bounds.width - margin * (cellCount + 1)) / cellCount
            
            itemSize = CGSize(width: width, height: width)
            
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        }
        
    }

}

// MARK: - 代理方法和数据源方法
extension CXLPicturePickerViewController{
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        // 选中张数大于 最大限制张数时,隐藏添加图片按钮
        return pictrues.count + ((pictrues.count == maxPictureCount) ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CXLPicturePickerViewCellID, forIndexPath: indexPath) as! CXLPicturePickerCell
        
        cell.picturePickerDelegate = self
        
        ///  item小于数组个数时,返回照片,否则返回nil
        cell.image = (indexPath.item < pictrues.count) ? pictrues[indexPath.item] : nil
        
        return cell
    }
    
}

// MARK: - 实现cell 代理方法
extension CXLPicturePickerViewController : CXLPicturePickerCellDelegate{
    
    ///  添加照片
    @objc private func picturePickerCellAddPicture(cell: CXLPicturePickerCell) {
        
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            
            print("没有权限")
            
            return
        }
        
        index = collectionView!.indexPathForCell(cell)!.item
        
        let pickerVC = UIImagePickerController()
        
        pickerVC.delegate = self
        
        presentViewController(pickerVC, animated: true, completion: nil)
        
    }
    ///  删除照片
    @objc private func picturePickerCellRemovePicture(cell: CXLPicturePickerCell) {

        let indexPath = collectionView!.indexPathForCell(cell)!
        
        pictrues.removeAtIndex(indexPath.item)
        
//        collectionView?.deleteItemsAtIndexPaths([indexPath])
    
        collectionView?.reloadData()
    }
}

// MARK: - 选择相册代理方法
extension CXLPicturePickerViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        let scaleImage = image.scaleImage()
        
        if index >= pictrues.count{
            
            pictrues.append(scaleImage)
            
        }else {
            
            pictrues[index] = scaleImage
        }
        
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}


//MARK: - CXLPicturePickerCellDelegate
@objc
private protocol CXLPicturePickerCellDelegate:NSObjectProtocol{
    
    optional func picturePickerCellAddPicture(cell: CXLPicturePickerCell)
    
    optional func picturePickerCellRemovePicture(cell: CXLPicturePickerCell)
}

//MARK: -自定义Cell
class CXLPicturePickerCell: UICollectionViewCell {
    
    /// 照片
    private var image:UIImage?{
        
        didSet{
            
            let addImage:UIImage = UIImage(named: "compose_pic_add")!
            
            addButton.setImage(image ?? addImage, forState: UIControlState.Normal)
            
            removeBtn.hidden = image == nil
        }
    }
    
    /// 定义代理
    private weak var picturePickerDelegate : CXLPicturePickerCellDelegate?
    
    //MARK:- 监听方法
    ///  添加图片
    @objc private func addPicture(){
        
        picturePickerDelegate?.picturePickerCellAddPicture?(self)
    }
    
    ///  删除图片
    @objc private func removePicture(){
        picturePickerDelegate?.picturePickerCellRemovePicture?(self)
    }
    
    
    //MARK:- 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor(white: 0.85, alpha: 1.0)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: -设置UI
    private func setupUI(){
        //添加控键
        contentView.addSubview(addButton)
        contentView.addSubview(removeBtn)
        
        //设置布局
        addButton.frame = contentView.bounds
        
        removeBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addButton.snp_top)
            make.right.equalTo(addButton.snp_right)
        }
        
        addButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        //添加监听方法
        
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeBtn.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
    }

    //MARK: - 懒加载
    //添加按钮
    private lazy var addButton:UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    
    private lazy var removeBtn:UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}
